'use strict';
const Response = require('../utils/response');
const path = require('path');
const fs = require('fs');
const mime = require('mime-types');
exports.template = async (ctx) => {
  let [name, type] = ctx.params.name.split('.');
  if (!type) {
    // 默认用js
    ctx.params.name += '.js';
    type = 'js';
    console.log(ctx.params.name, type);
  }
  let filePath = path.join(__dirname, '../../public', ctx.params.name);
  let fileBuffer = null;
  try {
    fileBuffer = fs.readFileSync(filePath);
  } catch (e) {
    // 找不到文件抛出错误
    return Response.fail(ctx, {
      code: 400,
      data: null,
      message: '没有找到文件'
    });
  }
  if (type === 'js' || type === 'txt') {
    return Response.success(ctx, {
      code: 200,
      data: {
        name: ctx.params.name,
        content: fileBuffer.toString()
      },
      message: 'success'
    });
  } else if (type === 'jpg' || type === 'png') {
    const mimeType = mime.lookup(filePath);
    ctx.set('content-type', mimeType);
    return ctx.body = fileBuffer;
  } else {
    console.log('类型不符合');
    return Response.fail(ctx, {
      code: 400,
      data: null,
      message: '不支持的文件类型'
    });
  }
};

exports.templates = async (ctx) => {
  const dirPath = path.join(__dirname, '../../public');
  const files = fs.readdirSync(dirPath);
  return Response.success(ctx, {
    code: 200,
    data: files,
    message: 'success'
  });
};
